﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Data;

namespace Songhay.Wpf.Mvvm.Extensions
{
    using Songhay.Wpf.Mvvm.ViewModels;

    /// <summary>
    /// Extension methods the base View Model.
    /// </summary>
    public static class ViewModelBaseExtensions
    {
        /// <summary>
        /// Dispatches the command in the specified Action Dictionary
        /// for invocation.
        /// </summary>
        /// <param name="viewModel">The view model.</param>
        /// <param name="commandName">Name of the command.</param>
        /// <param name="actionDictionary">The action dictionary.</param>
        public static void DoCommand(this ViewModelBase viewModel,
            string commandName, Dictionary<string, Action> actionDictionary)
        {
            if(actionDictionary.ContainsKey(commandName))
            {
                var action = actionDictionary[commandName];
                if(action != null) Application.Current.Dispatch(action);
            }
        }

        /// <summary>
        /// Sets the active view model to the specified collection item,
        /// causing WPF to display any view associated with the collection item.
        /// </summary>
        /// <typeparam name="ViewModelType">The type of the view model.</typeparam>
        /// <param name="viewModel">The view model.</param>
        /// <param name="collectionItem">The collection item.</param>
        /// <param name="collection">The collection.</param>
        public static void SetActiveViewModel<ViewModelType>(this ViewModelBase viewModel,
            ViewModelType collectionItem,
            ObservableCollection<ViewModelType> collection) where ViewModelType : ViewModelBase
        {
            Debug.Assert(collection.Contains(collectionItem));
            ICollectionView collectionView = CollectionViewSource.GetDefaultView(collection);
            if(collectionView != null) collectionView.MoveCurrentTo(collectionItem);
        }
    }
}
